<template>
  <div class="app-container">
    <div class="page-header">
      <h3>采购开单</h3>
    </div>

    <el-card class="form-card">
      <el-form :model="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="采购人：">
              <el-input v-model="form.createName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库仓库：">
              <el-select v-model="form.warehouseName" placeholder="请选择">
                <el-option v-for="item in warehouseList" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话：">
              <el-input v-model="form.purchaserPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注：">
              <el-input v-model="form.remark" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="goods-card" style="margin-top: 20px;">
      <el-button type="primary" @click="handleAddGoods">添加商品</el-button>

      <el-table :data="goodsList" style="width: 100%; margin-top: 10px;" size="small">
        <el-table-column prop="productName" label="商品名称" header-align="left" align="left" />
        <el-table-column prop="amount" label="数量" header-align="left" align="left" />
        <el-table-column label="操作" fixed="right" width="80">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleDeleteGoods(scope.row, scope.$index)" style="padding: 0 10px;">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="footer-container" style="margin-top: 20px; text-align: left;">
        <span>{{ goodsList.length }}种商品</span>
        <el-button type="primary" size="medium" style="margin-left: 20px;" @click="handleSubmit">
          添加采购订单
        </el-button>
      </div>
    </el-card>

    <!-- 添加商品弹窗 -->
    <el-dialog
      title="选择商品"
      :visible.sync="goodsDialogVisible"
      width="800px"
      :before-close="handleCloseDialog"
    >
      <div class="search-container">
        <el-select v-model="selectedCategory" placeholder="商品分类" style="width: 150px; margin-right: 10px;" @change="searchGoodsByCategory">
          <el-option v-for="item in categoryList" :label="item" :value="item" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="请输入商品名称"
          style="width: 300px; margin-right: 10px;"
          suffix-icon="el-icon-search"
          @keyup.enter.native="searchGoods"
        />
        <el-button type="primary" @click="searchGoods">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table :data="availableGoods" style="width: 100%; margin-top: 15px;" size="small">
        <el-table-column prop="productName" label="商品名称" header-align="left" align="left" />
        <el-table-column label="数量" header-align="left" align="left" width="120">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.amount"
              type="number"
              :min="1"
              style="width: 80px;"
              placeholder="0"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="100">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click="addToPurchaseList(scope.row)"
              :disabled="!scope.row.amount || scope.row.amount <= 0"
            >
              加入采购
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="confirmAddGoods">加入采购</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProductCategory,
  listProductList,
  listProductListByCategory,
  listWarehouseList,
  addOrder
} from "@/api/purchase/orderAppend";


export default {
  name: 'AppendPurchaseOrder',
  created() {
    // 加载仓库列表
    this.loadWarehouseList()
  },
  data() {
    return {
      form: {
        createName: '',
        purchaserPhone: '',
        warehouseName: '',
        remark: ''
      },
      goodsList: [
        { productName: '生抽', amount: 150 },
        { productName: '东北大米', amount: 600 }
      ],
      // 弹窗相关数据
      goodsDialogVisible: false,
      selectedCategory: '',
      searchKeyword: '',
      availableGoods: [],
      selectedGoods: [],
      // 商品分类列表
      categoryList: [],
      // 仓库列表
      warehouseList: []
    }
  },
  methods: {
    handleAddGoods() {
      // 重置弹窗数据
      this.searchKeyword = ''
      this.selectedCategory = ''
      this.selectedGoods = []
      this.categoryList = []

      // 加载商品列表
      this.searchGoods()


      // 加载商品分类数据
      this.searchGoodsCategory()


      // 显示弹窗
      this.goodsDialogVisible = true
    },

    searchGoods() {
      this.selectedCategory = undefined
      // 调用API获取商品列表，传递搜索关键词
      listProductList({ productName: this.searchKeyword }).then(response => {
        // 假设API返回的格式是 { code: 200, data: [...] }
        if (response.code === 200 && response.data) {
          // 处理后端返回的数据，确保每个商品有必要的字段
          this.availableGoods = response.data.map(item => ({
            productName: item.product_name || item.productName, // 兼容后端返回的字段名
            amount: null // 初始化为空
          }))
        } else {
          // 如果API调用失败或返回空数据，使用默认商品数据
          this.availableGoods = [
            { productName: '有机蔬菜一等生菜', amount: null },
            { productName: '东北大米', amount: null },
            { productName: '生抽', amount: null },
            { productName: '食用油', amount: null },
            { productName: '面粉', amount: null }
          ]
        }
      }).catch(() => {
        // 错误处理，使用默认商品数据
        this.availableGoods = [
          { goodsName: '有机蔬菜一等生菜', unit: '斤', quantity: null },
          { goodsName: '东北大米', unit: '袋', quantity: null },
          { goodsName: '生抽', unit: '瓶', quantity: null },
          { goodsName: '食用油', unit: '桶', quantity: null },
          { goodsName: '面粉', unit: '袋', quantity: null }
        ]
      })
    },
    //根据商品分类搜索商品
    searchGoodsByCategory(){
      //调用API通过商品分类搜索商品
      listProductListByCategory(this.selectedCategory).then(response =>{
        // 处理后端返回的数据，确保每个商品有必要的字段
        this.availableGoods = response.data.map(item => ({
          productName: item.product_name || item.productName, // 兼容后端返回的字段名
          amount: null // 初始化为空
        }))
      }).catch(() => {
        // 错误处理
        this.availableGoods = []
      })
    },

    // 重置搜索条件
    resetSearch(){
      this.searchKeyword = ''
      this.selectedCategory = ''
      this.searchGoods() // 重置后重新加载所有商品
    },

    // 搜索商品分类
    searchGoodsCategory() {
      // 调用API获取商品分类
      listProductCategory().then(response => {
        // 假设API返回的格式是 { code: 200, data: [...] }
        if (response.code === 200 && response.data) {
          // 根据实际返回的数据结构调整
          this.categoryList = response.data.map(item => item.categoryName || item)
        } else {
          // 如果API调用失败，使用默认分类
          this.categoryList = ['时令水果', '粮食作物', '有机蔬菜']
        }
      }).catch(() => {
        // 错误处理
        this.categoryList = ['时令水果', '粮食作物', '有机蔬菜']
      })
    },

    addToPurchaseList(row) {
      if (!row.amount || row.amount <= 0) {
        this.$modal.msgWarning('请输入有效的数量')
        return
      }

      // 检查商品是否已在采购列表中
      const existingIndex = this.goodsList.findIndex(item => item.productName === row.productName)

      if (existingIndex > -1) {
        // 如果已存在，则更新数量
        this.goodsList[existingIndex].amount += parseInt(row.amount)
      } else {
        // 如果不存在，则添加新商品
        this.goodsList.push({
          productName: row.productName,
          amount: parseInt(row.amount)
        })
      }

      // 清空当前行的数量
      row.amount = null

      this.$modal.msgSuccess('添加成功')
    },

    confirmAddGoods() {
      // 检查是否有选中并填写了数量的商品
      const hasSelectedGoods = this.availableGoods.some(item => item.amount && item.amount > 0)

      if (hasSelectedGoods) {
        // 将所有填写了数量的商品添加到采购列表
        this.availableGoods.forEach(row => {
          if (row.amount && row.amount > 0) {
            this.addToPurchaseList({...row})
          }
        })
      }

      this.goodsDialogVisible = false
    },

    handleCloseDialog() {
      this.goodsDialogVisible = false
    },

    handleDeleteGoods(row, index) {
      this.$confirm('确定要删除该商品吗？').then(() => {
        this.goodsList.splice(index, 1)
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },

    handleSubmit() {
      // 表单验证
      if (!this.form.createName) {
        this.$modal.msgError('请输入采购人')
        return
      }

      if (this.goodsList.length === 0) {
        this.$modal.msgError('请添加至少一种商品')
        return
      }

      // 构建提交数据，按照后端PurOrderDTO的结构
      const submitData = {
        purOrder: {
          purchaserName: this.form.createName,  // 采购人姓名
          purchaserPhone: this.form.purchaserPhone,  // 采购人电话
          warehouseName: this.form.warehouseName,  // 仓库名称
          remark: this.form.remark  // 备注
        },
        purOrderItems: this.goodsList.map(item => ({
          productName: item.productName,  // 商品名称
          purchaseQuantity: item.amount.toString()  // 采购数量，后端使用BigDecimal类型
        }))
      }

      // 提交订单
      addOrder(submitData).then(response => {
        this.$modal.msgSuccess('创建成功')
        // 使用组件名称跳转到订单管理页面
        setTimeout(() => {
          this.$router.push({ name: 'Order' })
        }, 500)
      }).catch(error => {
        this.$modal.msgError(error.msg || '创建失败')
        this.$modal.closeLoading()
        this.$modal.msgError('采购订单创建失败')
      })
    },
    // 处理关闭当前页面
    closeCurrentPage() {
      const { path, name, meta } = this.$route
      return this.$store.dispatch('tagsView/delView', { path, name, meta })
    },
    // 加载仓库列表
    loadWarehouseList() {
      listWarehouseList().then(response => {
        if (response.code === 200 && response.data) {
          this.warehouseList = response.data
        } else {
          this.warehouseList = []
        }
      }).catch(() => {
        this.warehouseList = []
      })
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.form-card {
  padding: 15px;
}

.goods-card {
  padding: 15px;
}

.footer-container {
  display: flex;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.search-container {
  margin-bottom: 15px;
  padding: 10px 0;
}

.el-button--primary {
  background-color: #1890ff;
  border-color: #1890ff;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-table .el-table__header-wrapper th {
  background-color: #fafafa;
}

.el-dialog__body {
  padding: 20px;
}

.dialog-footer {
  padding: 10px 20px 20px;
}
</style>
